from PySide import QtCore, QtGui

from OpenTonitruum.Source.DataSource import FileDataSource, AutoDataSource, DataSource

import matplotlib
matplotlib.use('Qt4Agg')
matplotlib.rcParams['backend.qt4'] = 'PySide'
matplotlib.rcParams['font.size'] = '7.0'
import pylab
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import os.path
from threading import Thread

class FileDataSourceView(object):
	defaultDirectory = FileDataSource.getDefaultDirectory()
	
	#class FileDataSourceLoad(QtCore.QThread):
	class FileDataSourceLoad(QtCore.QObject, Thread):
		addWidget = QtCore.Signal(object, object, int, int, int, int, str)
		
		def __init__(self, config):
			#super(FileDataSourceView.FileDataSourceLoad, self).__init__()
			Thread.__init__(self)
			QtCore.QObject.__init__(self)
			self.config = config
			self.allow_running = True
			
		def clearLayout(self):
			i = 0
			try:
				for column in range(self.config.parent.columnCount()):
					for row in range(self.config.parent.rowCount()):
						widget = self.config.parent.itemAtPosition(row, column)
						if widget is not None:
							widget.widget().deleteLater()
						i += 1
			except Exception as e:
				print i, ":",e
				pass
			
		def run(self):
			self.allow_running = True
			self.config.clearLayout()
			files = FileDataSource.getFilesInDirectory(self.config.dirname)
			col = 0
			row = 0
			for file in files:
				print 'Loading file source: ', file
				onlyfilename = os.path.splitext(os.path.basename(file))[0]
				try:
					y = []
					x = []
					dataSource = FileDataSource(file, self.config.scale, self.config.frequency_sample)
					for time, datapoint in dataSource:
						x.append(time)
						y.append(datapoint)
						if len(x) > 1000: break
					figure = Figure(figsize=(self.config.plot_size,self.config.plot_size), dpi=72, facecolor=(1,1,1), edgecolor=(0,0,0))
					figure.patch.set_alpha(0.3)
					subplot = figure.add_subplot(111)
					subplot.patch.set_alpha(0.5)
					subplot.set_title(onlyfilename, size = 12.0)
					subplot.plot(x, y)
					#self.addWidget.emit(figure, subplot, row, col, 1, 1, file)
					self.addWidget.emit(figure, subplot, row, col, 1, 1, onlyfilename)
				except Exception as e:
					print e
					pass
				if not self.allow_running:
					break
				col += 1
				if col == self.config.cols_number:
					row += 1
					col = 0
				
	def __init__(self, parent, dirname = None):
		super(FileDataSourceView, self).__init__()
		self._dirname = ""
		self._dirname_prev = ""
		self.dirname = dirname
		self.parent = parent
		self.frequency_sample = 1
		self.scale = 1
		self.cols_number = 3
		self.plot_size = 150
		self.runner = None
		#self.runner = FileDataSourceView.FileDataSourceLoad(self)
		#self.runner.addWidget.connect(self.addWidgetSource)
		
	def __del__(self):
		if self.runner is not None:
			self.runner.allow_running = False
			
	def clearLayout(self):
		i = 0
		try:
			for column in range(self.parent.columnCount()):
				for row in range(self.parent.rowCount()):
					widget = self.parent.itemAtPosition(row, column)
					if widget is not None:
						widget.widget().deleteLater()
					i += 1
		except Exception as e:
			print i, ":",e
			pass
	
	def setDirName(self, v):
		if v is None or v.strip() == "" or not os.path.isdir(v):
			self._dirname = FileDataSourceView.defaultDirectory
		else:
			self._dirname = v
	
	def getDirName(self):
		return self._dirname
	
	dirname = property(getDirName, setDirName)
	
	def run(self):
		if self._dirname_prev != self._dirname:
			#if self.runner.isRunning():
			if self.runner is not None and self.runner.isAlive():
				self.runner.allow_running = False
				self.runner.join()
				#self.runner.quit()
				#self.runner.terminate()
				#QtCore.QThread.cleanup()
			self.runner = FileDataSourceView.FileDataSourceLoad(self)
			self.runner.addWidget.connect(self.addWidgetSource)
			self.runner.start()
				
		self._dirname_prev = self._dirname

	def addWidgetSource(self, figure, subplot, row, col, spanrow, spancol, filename):
		canvas = FigureCanvas(figure)
		canvas._filename = filename
		canvas._row = row
		canvas._col = col
		canvas._selected = False
		canvas._figure = figure
		frame1 = subplot#.gca()
		frame1.axes.get_xaxis().set_visible(False)
		frame1.axes.get_yaxis().set_visible(False)
		canvas.setMinimumSize(QtCore.QSize(self.plot_size, self.plot_size))
		#canvas.setMaximumSize(QtCore.QSize(self.plot_size, self.plot_size))
		canvas.mpl_connect('button_press_event', self.clicked)
		#print type(canvas)
		#print dir(canvas)
		#print ">>>>", type(canvas.mousePressEvent)
		widget = QtGui.QWidget()
		vbox = QtGui.QVBoxLayout()
		label = QtGui.QLabel(filename)
		vbox.addWidget(canvas)
		vbox.addWidget(label)
		widget.setLayout(vbox)
		widget.setStyleSheet("background-color:rgba(0,0,0,10);border: 1px solid rgba(255,255,255,50);")
		widget.setSizePolicy( QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) )
		widget.setMinimumSize(QtCore.QSize(self.plot_size, self.plot_size))
		widget.setMaximumSize(QtCore.QSize(50+self.plot_size, 50+self.plot_size))
		#widget.setStyleSheet("background-color:rgba(0,0,0,150);border-radius:10px;border: 1px solid white;")
		#self.parent.addWidget(canvas, row, col, spanrow, spancol)
		canvas._widget = widget
		self.parent.addWidget(widget, row, col, spanrow, spancol)
	
	def clicked(self, e):
		#QtGui.QMessageBox.information(None, "example", e.canvas._filename)
		if e.canvas._selected:
			print 'was unselected'
			#e.canvas._figure.patch.set_facecolor('white')
			#e.canvas._figure.patch.set_color('white')
			#e.canvas._figure.set_alpha(1)
			e.canvas._widget.setStyleSheet("background-color:rgba(0,0,0,10);")
		else:
			print 'was selected'
			#e.canvas._figure.patch.set_facecolor('lightgoldenrodyellow')
			#e.canvas._figure.patch.set_color('lightgoldenrodyellow')
			#e.canvas._figure.set_alpha(1.0)
			e.canvas._widget.setStyleSheet("background-color:rgba(0,0,0,150);")
		#e.canvas._figure.patch.update()
		#e.canvas._figure.clear()
		#e.canvas.clear()
		#e.canvas.update()
		e.canvas._selected = not e.canvas._selected
	







